<?php

namespace App\Console\Commands;

use App\Models\ExtractCash;
use App\Models\Home\User;
use App\Models\MonthBalance;
use App\Repositories\UsersRepos;
use Carbon\Carbon;
use Illuminate\Console\Command;

class BalanceUserMonthEarnMoney extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'balance:money';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '收入结算';

    private $usersRepos;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(UsersRepos $usersRepos)
    {
        parent::__construct();
        $this->usersRepos = $usersRepos;
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $startTime = Carbon::now()->firstOfMonth();
        $endTime = Carbon::now()->endOfMonth();
        $userLists = User::all()->toArray();
        if (!empty($userLists)) {
            \DB::beginTransaction();
            $counts = 0;
            $flag = true;
            foreach ($userLists as $key => $value) {
                $extractCashModel = ExtractCash::select(\DB::raw('count(1) as total_nums'),\DB::raw('sum(cash_money) as total_cash_money'), \DB::raw('DATE_FORMAT(updated_at,\'%Y-%m\') as month'));
                $extractCashModel = $extractCashModel->where('extract_state',2);
                $extractCashModel = $extractCashModel->whereBetween('created_at',[$startTime,$endTime]);
        $extractCashModel = $extractCashModel->where('user_id',$value['id']);
                $monthBalance = $extractCashModel->groupBy('month')->get()->toArray();
                if (!empty($monthBalance)) {
                    $balance = $monthBalance[0];
                    $updateData = [];
                    $updateData['user_id'] = $value['id'];
                    $updateData['money'] = $balance['total_cash_money'];
                    $updateData['month'] = $balance['month'];
                    $updateData['total_earnings'] = $value['total_earnings'];
                    $res = MonthBalance::create($updateData);
                    if (!$res) {
                        \DB::rollBack();
                        $flag = false;
                        break;
                    }else{
                        $msgData['${month}'] = date('Y年m月',time());
                        $this->usersRepos->triggerMessage($value['id'],'结算通知',$msgData);
                        $counts ++ ;
                    }
                }
            }
            if ($flag) {
                \DB::commit();
                echo date('Y年m月',time())."结算成功，总共结算人数".$counts."人".PHP_EOL;
            }else{
                echo date('Y年m月',time())."总共数据库操作失败".PHP_EOL;
            }
        }
    }
}
